<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="mb-4">
      <el-form-item label="音色名称">
        <el-input
          v-model="queryParams.voiceName"
          placeholder="请输入音色名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="音色编码">
        <el-input
          v-model="queryParams.voiceCode"
          placeholder="请输入音色编码"
          clearable
        />
      </el-form-item>
      <el-form-item label="模型">
        <el-select
          v-model="queryParams.modelCode"
          placeholder="请选择模型"
          clearable
          style="width: 180px"
        >
          <el-option label="cosyvoice-v1" value="cosyvoice-v1" />
          <el-option label="cosyvoice-v2" value="cosyvoice-v2" />
          <el-option label="cosyvoice-v3" value="cosyvoice-v3" />
          <el-option label="cosyvoice-v3-plus" value="cosyvoice-v3-plus" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
        <el-button type="primary" plain icon="Plus" @click="addedVoicetones"
          >新增音色</el-button
        >
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" prop="id" align="center" />
      <el-table-column label="音色名称" prop="voiceName" align="center" />
      <el-table-column label="音色编码" prop="voiceCode" align="center" />
      <el-table-column label="模型名称" prop="modelName" align="center" />
      <el-table-column label="模型编码" prop="modelCode" align="center" />
      <el-table-column
        label="原始音频OSS中的访问路径"
        prop="trainUrl"
        align="center"
      />

      <el-table-column label="智能体" align="center">
        <template #default="scope">{{ scope.row.agentName || "-" }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleEdit(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="edVoicetonesEdit(scope.row)"
            >修改音色</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="open" :title="title" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="音色名称" prop="voiceName">
          <el-input v-model="form.voiceName" />
        </el-form-item>
        <el-form-item label="音色编码" prop="voiceCode" v-if="isEdit">
          <el-input v-model="form.voiceCode" />
        </el-form-item>
        <el-form-item label="模型" prop="modelCode">
          <el-select v-model="form.modelCode" placeholder="请选择模型">
            <el-option label="cosyvoice-v1" value="cosyvoice-v1" />
            <el-option label="cosyvoice-v2" value="cosyvoice-v2" />
            <el-option label="cosyvoice-v3" value="cosyvoice-v3" />
            <el-option label="cosyvoice-v3-plus" value="cosyvoice-v3-plus" />
          </el-select>
        </el-form-item>
        <el-form-item label="智能体名称" prop="agentName">
          <el-select
            v-model="form.agentId"
            placeholder="请选择智能体"
            filterable
            @change="onAgentChange"
          >
            <el-option
              v-for="item in agentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" />
        </el-form-item>
        <el-form-item label="音频文件" prop="trainUrl" >
          <el-upload
            class="upload-demo"
            action=""
            :http-request="uploadAudio"
            :limit="1"
            accept="audio/*"
            :on-remove="onAudioRemove"
          >
            <el-button type="primary">上传音频</el-button>
          </el-upload>

          <div v-if="form.trainUrl" style="margin-top: 10px">
            <audio :src="form.trainUrl" controls style="width: 100%"></audio>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑音色弹窗 -->
    <el-dialog v-model="openVoice" :title="title" width="600px">
      <el-form ref="voiceFormRef" :model="Voicefrom" label-width="120px">
        <el-form-item label="音色名称">
          <el-select v-model="Voicefrom.id" placeholder="请选择音色" filterable>
            <el-option
              v-for="item in VoicetList"
              :key="item.id"
              :label="item.voiceName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="音频文件" v-if="isEdit">
          <el-upload
            class="upload-demo"
            action=""
            :http-request="uploadVoiceAudio"
            :limit="1"
            accept="audio/*"
            :on-remove="onVoiceAudioRemove">
            <el-button type="primary">上传音频</el-button>
          </el-upload>

          <div v-if="Voicefrom.url" style="margin-top: 10px">
            <audio
              :src="Voicefrom.url"
              controls
              style="width: 100%"
            ></audio>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="openVoice = false">取消</el-button>
        <el-button type="primary" @click="submitVoiceForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  pageVoices,
  addVoice,
  updateVoice,
  deleteVoice,
  getVoiceInfo,
  listAIAgent,updateTimbre,createTimbre
} from "@/api/system/voices"; // 接口封装
import { getToken } from "@/utils/auth";

const loading = ref(false);
const total = ref(0);
const list = ref([]);
const open = ref(false);
const title = ref("");
const formRef = ref(null);
const agentList = ref([]);
const VoicetList = ref([]);
const voiceFormRef = ref(null);
const isEdit = ref(false);
const openVoice = ref(false);

// 分页和搜索参数
const queryParams = reactive({
  page: 1,
  size: 10,
  voiceName: "",
  voiceCode: "",
  modelCode: "",
});

// 表单数据
const form = reactive({
  id: null,
  voiceName: "",
  voiceCode: "",
  modelCode: "",
  agentId: null,
  agentName: "",
  remark: "",
  trainUrl: "",
});
// 表单数据
const Voicefrom = reactive({
  id: null,
  url: "",
});

// 表单校验规则
const rules = {
  voiceName: [{ required: true, message: "请输入音色名称", trigger: "blur" }],
  // voiceCode: [{ required: true, message: "请输入音色编码", trigger: "blur" }],
  modelCode: [{ required: true, message: "请选择模型", trigger: "change" }],
};

// 页面初始化
onMounted(() => {
  getList();
});

// 获取音色列表
async function getList() {
  loading.value = true;
  try {
    const res = await pageVoices(queryParams);
    if (res.code === 0 || res.code === 200) {
      list.value = res.data.records || [];
      total.value = Number(res.data.total) || 0;
    }
  } finally {
    loading.value = false;
  }
}

// 重置搜索
function resetQuery() {
  queryParams.voiceName = "";
  queryParams.voiceCode = "";
  queryParams.modelCode = "";
  queryParams.page = 1;
  getList();
}

// 新增
function handleAdd() {
  title.value = "新增";
  Object.assign(form, {
    id: null,
    voiceName: "",
    modelCode: "",
    agentId: null,
    agentName: "",
    remark: "",
    trainUrl: "",
  });
  open.value = true;
  isEdit.value = false;
  getAgentList();
}

// 编辑
async function handleEdit(row) {
  title.value = "编辑";

  const res = await getVoiceInfo(row.id);
  if (res.code === 0 || res.code === 200) {
    Object.assign(form, res.data);
    isEdit.value = true;
    open.value = true;
  } else {
    ElMessage.error(res.msg || "获取详情失败");
  }
  getAgentList();
}

function onAgentChange(id) {
  const agent = agentList.value.find((item) => item.id === id);
  form.agentName = agent ? agent.name : "";
}

// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate();
    let res;
    if (form.id) {
      res = await updateVoice(form);
    } else {
      // 新增音色接口
      res = await addVoice(form);
    }
    if (res.code === 0 || res.code === 200) {
      ElMessage.success("操作成功");
      open.value = false;
      getList();
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (err) {
    console.log("表单验证失败或操作异常", err);
  }
}
function getVoiceToneList() {
  pageVoices({
    page: 1,
    size: 999,
  }).then((res) => {
    VoicetList.value = res.data?.records || [];
  });
}

function addedVoicetones(params) {
  title.value = "新增音色";
  Object.assign(Voicefrom, {
    id: null,
  });
  openVoice.value = true;
   isEdit.value = false;
  getVoiceToneList();
}

async function edVoicetonesEdit(row) {
    title.value = "编辑";

  const res = await getVoiceInfo(row.id);
  if (res.code === 0 || res.code === 200) {
    Object.assign(Voicefrom, res.data);
    isEdit.value = true;
    openVoice.value = true;
  } else {
    ElMessage.error(res.msg || "获取详情失败");
  }
 getVoiceToneList();
  
}
async function submitVoiceForm() {
  try {
    await voiceFormRef.value.validate();

    let res;

    if (!isEdit.value) {
      // 新增音色，只需要 ID
      res = await createTimbre(Voicefrom.id);
    } else {
      // 编辑音色，需要 id + url
      res = await updateTimbre({
        id: Voicefrom.id,
        url: Voicefrom.url
      });
    }

    if (res.code === 0 || res.code === 200) {
      ElMessage.success("操作成功");
      openVoice.value = false;
      getList();
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (e) {
    console.error(e);
  }
}



async function uploadVoiceAudio(option) {
  const file = option.file;
  const formData = new FormData();
  formData.append("file", file);
  formData.append("dir", "admin");

  try {
    const res = await fetch("/dev-api/user/file/oss/upload", {
      method: "POST",
      headers: {
        "Authorization-Admin": getToken(),
      },
      body: formData,
    });

    const data = await res.json();
    if (data.code === 0 || data.code === 200) {
      Voicefrom.url = data.data.url; 
      ElMessage.success("音频上传成功");
    } else {
      ElMessage.error(data.msg || "上传失败");
    }
  } catch (err) {
    ElMessage.error("上传失败");
  }
}


// 当删除已上传音频时触发
function onVoiceAudioRemove(file, fileList) {
  Voicefrom.url = ""; // 清空表单中的音频 URL
  ElMessage.info("音频已移除");
}

async function uploadAudio(option) {
  const file = option.file;
  const formData = new FormData();
  formData.append("file", file);
  formData.append("dir", "admin");

  try {
    const res = await fetch("/dev-api/user/file/oss/upload", {
      method: "POST",
      headers: {
        "Authorization-Admin": getToken(),
      },
      body: formData,
    });

    const data = await res.json();
    if (data.code === 0 || data.code === 200) {
      // 上传成功，把返回的 url 赋值给表单的 trainUrl
      form.trainUrl = data.data.url;
      ElMessage.success("音频上传成功");
    } else {
      ElMessage.error(data.msg || "上传失败");
    }
  } catch (err) {
    ElMessage.error("上传失败");
    console.error(err);
  }
}

// 当删除已上传音频时触发
function onAudioRemove(file, fileList) {
  form.trainUrl = ""; // 清空表单中的音频 URL
  ElMessage.info("音频已移除");
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm("确认删除该音色吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteVoice(row.id);
      if (res.code === 0 || res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    })
    .catch(() => {});
}

function getAgentList() {
  listAIAgent({
    page: 1,
    size: 999,
    agentType: -1,
    isActive: 0,
  }).then((res) => {
    agentList.value = res.data?.records || [];
  });
}
</script>
